package ws.very.util.lang

import java.rmi.registry.LocateRegistry
import java.rmi.server.RemoteServer
import java.rmi.server.UnicastRemoteObject
import java.rmi.RemoteException
import java.rmi.Naming
import java.rmi.Remote

object RMIs {

  def update(serviceName: String, addressInfo: (String, Int) = ("localhost", 1122)) =
    bind(addressInfo._1, addressInfo._2, serviceName)
  def apply[R](serviceName: String, addressInfo: (String, Int) = ("localhost", 1122)) =
    loopup(addressInfo._1, addressInfo._2, serviceName)
  @remote
  trait RmiService {
    @throws(classOf[RemoteException])
    def apply[R](fn: => R): R
  }
  class RmiServiceImpl1 extends UnicastRemoteObject with RmiService {
    def apply[R](fn: => R): R = fn
  }

  def bind(ip: String, port: Int, serviceName: String) = {
    val rmiService = new RmiServiceImpl1
    LocateRegistry.createRegistry(port)
    Naming.rebind("rmi://" + ip + ":" + port + "/" + serviceName, rmiService)
  }

  def loopup(ip: String, port: Int, serviceName: String): RmiService =
    Naming.lookup("rmi://" + ip + ":" + port + "/" + serviceName).asInstanceOf[RmiService]

  def clientHost = RemoteServer.getClientHost

}
